<?php
/**
 * @Copyright (c) 2011, 新浪网运营部-网络应用开发部
 * All rights reserved.
 * 通用函数
 * @author          wangxin <wangxin3@staff.sina.com.cn>
 * @time            2011/3/2 11:48
 * @version         Id: 0.9
*/

class BaseModelCommon {
    
    //禁止实例化
    private function __construct() {
        return;
    }

    /**
     * 二维数组根据自动字段排序
     * @param array $data 需要排序的数组
     * @param string $orderby_key 依据字段
     * @param string $type 排序方式，desc|asc
     * @return 排序完成数组
     */
    static public function arrayOrderBy($arr, $orderby_key, $type = 'ASC') {
        $col = array();
        foreach ($arr as $key => $value)
        {
            $col[$key] = $value[$orderby_key];
        }

        $type = (strtoupper($dir) == "ASC" ? SORT_ASC : SORT_DESC);

        array_multisort($col, $type, $arr);
        return $arr;
    }
    
	/**
	 * 转码函数
	 * @param $data Mixed
	 * @param $dstEncoding String
	 * @param $srcEncoding String
	 * @return
	 */
	static public function convertEncoding($data, $dstEncoding, $srcEncoding) {
		if(!is_array($data)) {
			$data = mb_convert_encoding($data, $dstEncoding, $srcEncoding);
		} else {
			foreach($data as $key=>$value) {
                if (is_numeric($value)) {
                    continue;
                }
				$data[$key] = self::convertEncoding($value, $dstEncoding, $srcEncoding);
			}
		}
		return $data;
	}
    
    /**
     * 递归创建目录
     */
    public static function recursiveMkdir($pathname, $mode=0700) {
        if (PLATFORM == 'ase') {
        } else {
    		is_dir(dirname($pathname)) || self::recursiveMkdir(dirname($pathname), $mode);
        	return is_dir($pathname) || mkdir($pathname, $mode);
        }
	}
    
    /**
      * 返回程序开始到调用函数处的执行时间
      * @return time
      */
    static public function getRunTime() {
        $time = explode(" ", STARTTIME);
	    $startTime = (double)$time[1] + (double)$time[0];
        $time = explode(" ", microtime());
	    $nowTime = (double)$time[1] + (double)$time[0];
        return sprintf("%0.3f", $nowTime - $startTime) . " s";
    }
    
    /**
      * 返回程序开始到调用函数处的执行时间
      * @return time
      */
    static public function debug($value, $type = 'DEBUG', $showTime = '') {
        if (DEBUG === 1) {
            if (@strpos(DEBUG_DISABLED_OUT, $type) === false || @strpos(HttpParams::get('firephp'), $type) !== false) { 
                if (defined('QUEUE')) {
                    echo date("Y-m-d H:i:s") . " " . $type . ": " . $value . "\n";
                } elseif (DEBUG_OUT == "phpfire") {
                    if ($type == 'SQL' && preg_match("/^UPDATE|^DELETE|^INSERT|^REPLACE|^ALTER|^TRUNCATE|^CREATE/i", $value)) {
                        FirePHP::getInstance(true)->warn($value, $type);
                    } else {
                        FirePHP::getInstance(true)->log($value, $type);
                    }
                    if ($showTime == 1) {
                        FirePHP::getInstance(true)->log(self::getRunTime(), 'runTime');
                    }
                }
                if (@strpos(DEBUG_HTTP_OUT, $type) !== false) {
                    $msg = urlencode($type . "：" . $value . self::getRunTime() . "【".$_SERVER[PHP_SELF]."】");
                    BaseModelHttp::sendRequest("http://club.service.sina.com.cn/api/tmp_log/set_tmp_log.php?type=20&log={$msg}");
                }   
            }   
        } 
    }
    
    /**
	 * 类/函数名构造
	 * @param $name String 传入名
	 * @param $type String 类型：function | class
	 * @return string
	 */
    static public function getFormatName($name, $type = 'function') {
    	$name = explode('_', $name);
    	for($i = 0, $len = count($name); $i < $len; $i++ ) {
            if ($type != "class" && $i == 0) {
                $name[$i] = strtolower($name[$i]);
            } else {
    	    	$name[$i] = ucfirst(strtolower($name[$i]));
            }
    	}
    	return implode('', $name);
	}
    
    
    /**
	 * checkbox选框值格式化
	 * @param $arr arr 传入多选数组
	 * @return string 格式化后的字符串
	 */
    static public function checkboxStrEncode($arr) {
    $str = 'SELECTED:[';
    if(is_array($arr)){
        foreach($arr as $v){
            $str .= "'".$v."'";
        }
    }
    $str .= ']';
    return $str;
    }

    /**
	 * checkbox选框值反格式化
	 * @param $arr arr 传入格式化后的字符串
	 * @return string 多选数组
	 */
    static public function checkboxStrDecode($str) {
        $arr = $matches = array();
        preg_match("/^SELECTED:\[(.*)\]$/", $str, $matches);
        $str = str_replace('\'','"',"[".$matches[1]."]");
        $arr = json_decode($str,true);
        return $arr;
    }
}
